import { createServer } from "node:http";
import Koa from "koa";
import { Server } from "socket.io";
import serve from "koa-static";
import Router from "@koa/router";
import cors from "@koa/cors";
import path from "path";
import * as fs from "node:fs";

const router = new Router();
const app = new Koa();
app.use(cors());

/**
 * 1-先设置静态资源目录，例如 public 目录
 */
// 设置静态资源目录，例如 public 目录
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const staticDir = path.join(__dirname, "./public");
// 使用 koa-static 中间件
app.use(serve(staticDir));

/**
 * 2-然后设置路由
 */
// router.get("/index", (ctx) => {
// 	ctx.body = html;
// });
app.use(router.routes());

const httpServer = createServer(app.callback());
const io = new Server(httpServer, {
	cors: {
		origin: "*",
		methods: ["GET", "POST"],
	},
});

// 处理 socket 连接
io.on("connect", (client) => {
	client.on("event", (data) => {
		console.log(data);
	});
	client.on("message", (data) => {
		console.log("message:", data);
	});
	client.on("disconnect", (data) => {
		console.log("disconnect:", data);
	});
});

/**
 * 一定要用 httpServer.listen 监听端口，而不是 app.listen
 * 如果是用 app.listen 监听端口，会导致 socket.io 无法正常工作
 */
httpServer.listen(3000, () => {
	console.log("server running at http://localhost:3000");
});
